package demo1;

import java.util.Arrays;

/**
 * Description:
 * Date: 2025-10-16
 * Time: 20:47
 */
public class Test {
    public static void main1(String[] args) {
        Student student1 = new Student("zhangsan",18);
        Student student2 = new Student("lisi",21);

        //如何去比较一个自定义的类？--> 实现Comparable接口
        System.out.println(student1.compareTo(student2));
    }

    //以Comparable接口作为参数接收，可以实现统一性，只有实现了Comparable接口的类才能往这个方法中进行传参
    public static void mySort(Comparable[] comparables) {
        //以冒泡排序的规范写
        for (int i = 0; i < comparables.length; i++) {
            for (int j = 0; j < comparables.length - 1 - i; j++) {
                if(comparables[j].compareTo(comparables[j+1]) > 0){
                    Comparable tmp = comparables[j];
                    comparables[j] = comparables[j+1];
                    comparables[j+1] = tmp;
                }
            }
        }

    }

    public static void main2(String[] args) {
        //问题：如果有多个同一类该怎么比？--> 放进数组中进行排序
        Student[] students = new Student[3];
        students[0] = new Student("zhangsan",18);
        students[1] = new Student("lisi",21);
        students[2] = new Student("wangwu",15);

        System.out.println("排序前：" + Arrays.toString(students));

        //你想要进行比较，那就必须得实现compareable接口，重写compareTo()方法
        Arrays.sort(students);//这个排序是调用Student类中自己重写的compareTo()方法

        mySort(students);
        System.out.println("排序后：" + Arrays.toString(students));
    }

    public static void main3(String[] args) {
        //第二种比较方法--> 使用Comparator接口实现 比较器
        Student[] students = new Student[3];
        students[0] = new Student("zhangsan",18);
        students[1] = new Student("lisi",21);
        students[2] = new Student("wangwu",15);
        System.out.println("排序前：" + Arrays.toString(students));
        AgeComparator ageComparator = new AgeComparator();
        NameComparator nameComparator = new NameComparator();
        //第二个解决方法，实现一个比较器，传入sort()的第二个参数
        //此时students中进行的比较与本身有没有实现comparable接口无关，因为它自带了一个比较器过去
        //这就实现了解耦（能够灵活的进行比较）
        //Arrays.sort(students,ageComparator);
        Arrays.sort(students,nameComparator);

        System.out.println("排序后：" + Arrays.toString(students));
    }

    public static void swap(MyVal myVal1, MyVal myVal2){
        int tmp = myVal1.val;
        myVal1.val = myVal2.val;
        myVal2.val = tmp;
    }

    public static void main(String[] args) {
        //如何通过方法将两个数的值进行叫换
        //将值存放在对象的引用中，实现将值通过方法来进行在堆上的交换
        MyVal val1 = new MyVal();
        MyVal val2 = new MyVal();
        val1.val = 10;
        val2.val = 20;

        System.out.println("交换前,val1 = " + val1.val + "  val2 = " + val2.val);
        swap(val1,val2);
        System.out.println("交换后,val1 = " + val1.val + "  val2 = " + val2.val);

    }
}
